package cn.hdu.liang.ch7;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class RLDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        final ReentrantLock lock = new ReentrantLock();

        class Worker implements Runnable {
            private final String name;

            Worker(String name) {
                this.name = name;
            }

            @Override
            public void run() {
                lock.lock();
                try {
                    if(lock.isHeldByCurrentThread()) {
                        System.out.printf("线程 %s 进入临界区.%n", name);
                    }
                    System.out.printf("线程 %s 执行工作.%n", name);

                    try {
                        Thread.sleep(2000);
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.printf("线程 %s 完成工作.%n", name);
                } finally {
                    lock.unlock();
                }
            }
        }

        executor.execute(new Worker("ThdA"));
        executor.execute(new Worker("ThdB"));

        try {
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch(InterruptedException ie) {
            ie.printStackTrace();
        }

        executor.shutdownNow();
    }
}
